import { clearSearchResult, getSearchResult } from "@/store/actions/search";
import React, { memo, useEffect, useState, useRef } from "react";
import { useSelector, useDispatch } from "react-redux";
import { useLocation, Link } from "react-router-dom";
import styles from "./result.module.scss";
import Icon from "@/components/icon";
import Header from "@/shared/header";
import Back from "@/shared/back";
import { Image, InfiniteScroll, PullToRefresh, Skeleton } from "antd-mobile";
const Result = memo(() => {
  const location = useLocation();
  const dispatch = useDispatch();
  const containerRef = useRef(null); // 使用 useRef 创建容器的 ref
  const [isHasMore, setIsHasMore] = useState(true); // 是否还有更多数据
  const [isLoading, setIsLoading] = useState(true);
  // 从 URL 中获取搜索关键词
  const params = new URLSearchParams(location.search);
  const q = params.get("q") ?? "";

  // 从 Redux store 中获取搜索结果和相关状态
  const { searchResults } = useSelector((state: any) => state.search);
  const { results, total_count, page } = searchResults;

  // 页面初始化时获取搜索结果
  useEffect(() => {
    const fetchData = async () => {
      try {
        await dispatch(getSearchResult(q, 1) as any);
        setIsLoading(false);
      } catch (error) {
        // 处理错误
        console.error("Failed to fetch data:", error);
      }
    };

    fetchData(); // 调用异步函数

    return () => {
      dispatch(clearSearchResult() as any);
    };
  }, [dispatch, q]);

  // 监听搜索结果变化，更新是否还有更多数据的状态
  useEffect(() => {
    setIsHasMore(results.length < total_count);
  }, [results, total_count]);

  // 加载更多数据的函数
  const loadMore = async () => {
    if (page > 1) {
      await dispatch(getSearchResult(q, page + 1) as any); // 获取下一页的数据
    }
  };

  // 上拉刷新数据的函数
  const onRefresh = async () => {
    await dispatch(getSearchResult(q, 1) as any); // 重新获取第一页的数据
  };

  return (
    <div>
      <PullToRefresh onRefresh={onRefresh}>
        {/* 顶部固定部分 */}
        <div className={styles.HeadContainer}>
          <Header title="搜索结果" left={<Back />} />
        </div>

        {/* 自适应滚动的 body 部分 */}
        {isLoading ? (
          <div>
            <Skeleton.Title animated />
            <Skeleton.Paragraph lineCount={5} animated />
          </div>
        ) : (
          <div
            ref={containerRef} // 绑定容器的 ref
            className={styles.container} // 使用 container 类名代替 id 选择器
          >
            <ul className={styles.news}>
              {results.map((item: any, index: any) => (
                <li className={styles.hasMorePicture} key={index}>
                  <div className={styles.main}>
                    <Link
                      className={styles.title}
                      to={`/articles/${item.art_id}`}
                    >
                      {item.title}
                    </Link>
                    <Link
                      className={item.cover.images ? styles.imgContainer : ""}
                      to={`/articles/${item.art_id}`}
                    >
                      {item.cover.images &&
                        item.cover.images.map((itemSrc: any, index: any) => (
                          <Image src={itemSrc} alt="" key={index} />
                        ))}
                    </Link>
                  </div>
                  <div className={styles.secondary}>
                    <Link
                      to={`/articles/${item.art_id}`}
                      className={styles.meta}
                    >
                      <span className={styles.item}>{item.aut_name}</span>
                      <span className={styles.item}>{item.comm_count}评论</span>
                      <span className={styles.item}>
                        {item.collect_count}年内
                      </span>
                    </Link>
                    <Icon
                      type={"iconbtn_channel_close"}
                      className={styles.close}
                    />
                  </div>
                </li>
              ))}
              {/* 使用 InfiniteScroll 组件实现无限滚动加载更多数据 */}
              <InfiniteScroll loadMore={loadMore} hasMore={isHasMore} />
            </ul>
          </div>
        )}
      </PullToRefresh>
    </div>
  );
});

export default Result;
